import Node from './Node';

/**
 * 获取包含 element 的组件列表, 从里到外返回
 * @param element
 * @param app
 * @returns
 */
const getWrapperNodeLoop = (element?: HTMLElement | null): Node[] => {
  const result: Node[] = [];
  let elementPtr = element;

  while (elementPtr) {
    if (elementPtr === document.body) {
      break;
    }
    const node = getWrapperNode(elementPtr);
    if (node) {
      result.push(node);
    }
    elementPtr = elementPtr?.parentElement;
  }

  return result;
};

/**
 * 获取包含 element 的组件
 * @param element
 * @returns
 */
const getWrapperNode = (element?: HTMLElement | null) => {
  if (element?.dataset.id) {
    const node = window.appCore.page?.getNode(element.dataset.id);
    if (node) {
      return node;
    }
  }
};

class Event {
  /**
   * 初始化
   */
  init() {
    this.bindPanelEvents();
    this.bindStageEvents();
  }

  /**
   * 绑定 2d 面板事件
   */
  bindPanelEvents() {
    window.document.body.addEventListener('click', this.panelClickEventHandler);
    window.document.body.addEventListener('mousemove', this.panelMousemoveEventHandler);
  }

  /**
   * 解绑 2d 面板事件
   */
  unbindPanelEvents() {
    window.document.body.removeEventListener('click', this.panelClickEventHandler);
    window.document.body.removeEventListener('mousemove', this.panelMousemoveEventHandler);
  }

  panelClickEventHandler(e: MouseEvent) {
    const nodes = getWrapperNodeLoop(e.target as HTMLElement);
    if (!nodes) {
      return;
    }
    window.appCore.emit('click', nodes);
  }

  panelMousemoveEventHandler(e: MouseEvent) {
    const nodes = getWrapperNodeLoop(e.target as HTMLElement);
    if (!nodes) {
      return;
    }
    window.appCore.emit('mousemove', nodes);
  }

  /**
   * 绑定 3d 场景事件
   */
  bindStageEvents() {
    const { cimInstance } = window;
    cimInstance.api.addPickerEventListener('mouse_leftclick', this.stageClickEventHandler);
  }

  /**
   * 解绑 3d 场景事件
   */
  unbindStageEvents() {
    const { cimInstance } = window;
    cimInstance.api.removePickerEventListener('mouse_leftclick', this.stageClickEventHandler);
  }

  /**
   * 场景点击回调
   * @param startPositionPicked - 点击场景所拾取到的对象（从clickAction.position获取）
   * @param endPositionPicked - 点击场景所拾取到的对象（从clickAction.endPosition获取）
   * @param clickAction - cesium场景中setInputAction默认原始的callback的参数
   * @param info - {name:对象的name,id:对象的id,layerType:图层类型,layerName:图层的名字}
   * @returns
   */
  stageClickEventHandler(
    startPositionPicked: any,
    endPositionPicked: any,
    clickAction: any,
    info: any
  ) {
    if (!info.id) {
      return;
    }
    const node = window.appCore.page?.getNode(info.id);
    if (!node) {
      return;
    }
    window.appCore.emit('click', [node]);
  }

  /**
   * 销毁实例
   */
  dispose() {
    this.unbindPanelEvents();
    this.unbindStageEvents();
  }
}

export default Event;
